﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
 

namespace ApiServiceA.Controllers
{
    [ApiController]
    //[Route("[controller]")]
    [Route("api")]

    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private IMemoryCache _memoryCache; 

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IMemoryCache memoryCache)
        {
            _logger = logger;
            _memoryCache = memoryCache;
        }

        [HttpGet]
        [Route("Get")]
        public async Task<IActionResult> GetAsync()
        {
            Console.WriteLine(nameof(ApiServiceA)+ $"time is :{DateTime.Now}"); 
            var result = await Task.Run(() =>
            {
                return $"This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}, time is :{DateTime.Now}";

            });
            return Ok(result);
        }

        [HttpGet]
        [Route("Get2")]
        public async Task<IActionResult> Get2Async()
        {
            Console.WriteLine(nameof(ApiServiceA) + $"time is :{DateTime.Now}");
            string cacheKey = "sname";//要区分是谁的缓存
             
            //缓存设置,
            if (!_memoryCache.TryGetValue(cacheKey, out string cacheResult))
            {
                cacheResult = DateTime.Now.ToString();
                //设置相对过期时间5秒钟,即5秒未访问清理缓存
                //_memoryCache.Set("sname", cacheResult, new MemoryCacheEntryOptions()
                //    .SetSlidingExpiration(TimeSpan.FromSeconds(5)));
                //设置绝对过期时间5秒钟,即5秒清理缓存
                _memoryCache.Set("sname", cacheResult, new MemoryCacheEntryOptions()
                  .SetAbsoluteExpiration(TimeSpan.FromSeconds(5)));
                /*                //移除缓存
                                _memoryCache.Remove(cacheKey);
                                //缓存优先级 （程序压力大时，会根据优先级自动回收）
                                _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
                                    .SetPriority(CacheItemPriority.NeverRemove));*/
                /*                //缓存回调 10秒过期会回调
                                _memoryCache.Set(cacheKey, cacheResult, new MemoryCacheEntryOptions()
                                    .SetAbsoluteExpiration(TimeSpan.FromSeconds(10))
                                    .RegisterPostEvictionCallback((key, value, reason, substate) =>
                                    {
                                        Console.WriteLine($"键{key}值{value}改变，因为{reason}");
                                    }));*/
                /* //缓存回调 根据Token过期
                 var cts = new CancellationTokenSource();
                 _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
                     .AddExpirationToken(new CancellationChangeToken(cts.Token))
                     .RegisterPostEvictionCallback((key, value, reason, substate) =>
                     {
                         Console.WriteLine($"键{key}值{value}改变，因为{reason}");
                     }));
                 cts.Cancel();*/

            }
            Console.WriteLine(cacheResult);

            var result = await Task.Run(() =>
            {
                return $"This is from {HttpContext.Request.Host.Value}, path: {HttpContext.Request.Path}, time is :{DateTime.Now}";

            });
            return Ok(result);
        }

        /* public IEnumerable<WeatherForecast> Get()
         {
             var rng = new Random();
             return Enumerable.Range(1, 5).Select(index => new WeatherForecast
             {
                 Date = DateTime.Now.AddDays(index),
                 TemperatureC = rng.Next(-20, 55),
                 Summary = Summaries[rng.Next(Summaries.Length)]
             })
             .ToArray();
         }*/
    }
}
